<template>
    <div style="padding-bottom:20px">
        <div class="text-right margin-bottom-20">
            <i-button type="primary" @click="initData">刷新列表</i-button>
        </div>

        <Table :data="tableData" :columns="columns" :loading="loading"></Table>

        <div class="text-center margin-top-20">
            <Page
                show-total
                :current.sync="pagination.current"
                :total="pagination.total"
                :page-size="pagination.limit"
                @on-change="initData"
            />
        </div>

        <member-detail
            :visible.sync="memberDetail.visible"
            :name="memberDetail.name"
            :phone="memberDetail.phone"
            :user-id="memberDetail.userId"
            :face-id="memberDetail.faceId"
            :role-id="memberDetail.roleId">
        </member-detail>
    </div>
</template>

<script>
    import { date, dayTimeStamp } from '@/libs/date'
import { http, api } from '@/libs/http'
import { faceAccessAuthType } from '@/libs/const'
import { memberDetail } from '@/components'

export default {
      name: 'access-auth-history',
      props: {
        deviceInfo: Object,
        roomId: Number
      },
      components: {
        memberDetail
      },
      data () {
        return {
          loading: false,
          tableData: [],
          memberDetail: {
            userId: 0,
            roleId: 0,
            faceId: 0,
            phone: '',
            name: '',
            visible: false
          },
          pagination: {
            current: 1,
            total: 0,
            limit: 20
          },
          operationActions: {
            reauthorize: {
              label: '重新执行',
              handler: 'handleReauthorize'
            },
            cancelAuth: {
              label: '取消授权',
              handler: 'handleCancelAuth'
            }
          },
          authStatus: {
            1: '待生效',
            2: '待生效',
            3: '已生效',
            4: '已失效'
          },
          opStateMap: {
            11: {
              label: '授权添加中',
              actions: []
            },
            12: {
              label: '添加授权失败',
              actions: [ 'reauthorize', 'cancelAuth' ]
            },
            13: {
              label: '添加授权成功',
              actions: [ 'cancelAuth' ]
            },
            21: {
              label: '修改授权中',
              actions: []
            },
            22: {
              label: '修改授权失败',
              actions: [ 'reauthorize', 'cancelAuth' ]
            },
            23: {
              label: '修改授权成功',
              actions: [ 'cancelAuth' ]
            },
            31: {
              label: '取消授权中',
              actions: []
            },
            32: {
              label: '取消授权失败',
              actions: [ 'reauthorize' ]
            },
            33: {
              label: '取消授权成功',
              actions: []
            }
          },
          columns: [
            { title: '编号', key: 'id' },
            { title: '状态', key: 'authStatus' },
            {
              title: '授权有效期',
              render: (h, p) => {
                const format = 'YYYY-MM-DD HH:mm'
                const [ start, end ] = p.row.auth_time_range
                if (new Date(start).getTime() + 50 * 365 * dayTimeStamp < new Date(end).getTime()) {
                  return <span>永久有效</span>
                }
                return <div>
                  <div>{date(start, format)}</div>
                  <div>{date(end, format)}</div>
                </div>
              }
            },
            {
              title: '姓名',
              render: (h, p) => <a href='javascript:;' onClick={() => this.handleMemberDetail(p.row)}>{p.row.userInfo}</a>
            },
            { title: '备注', key: 'authRemark' },
            {
              title: '操作',
              render: (h, { row }) => {
                const { operationActions } = this
                return row.actions.map(action => (
                  <i-button
                    size='small'
                    onClick={() => this.handleOp(operationActions[action].handler, row)}
                  >
                    {operationActions[action].label}
                  </i-button>
                ))
              }
            }
          ]
        }
      },
      created () {
        this.initData()
      },
      methods: {
        async initData () {
          try {
            this.loading = true
            const { limit, current } = this.pagination
            const params = {
              limit,
              offset: (current - 1) * limit
            }
            const res = await http.req(api.face_access_auth_history, [ this.roomId, this.deviceInfo.id ], params)
            if (res) {
              this.pagination.total = res.count
              res.rows.forEach(item => {
                const { auth_time_range, op_state, op_err_msg, auth_state, relation_role, relation_name } = item
                const op = this.opStateMap[op_state]
                const isExpired = auth_time_range[1] && new Date(auth_time_range[1]).getTime() < Date.now()
                item.actions = (op && op.actions) || []
                item.authRemark = (op && op.label) + ([12, 22, 32].includes(Number(op_state)) ? `(${op_err_msg})` : '')
                item.authStatus = isExpired ? '已过期' : (this.authStatus[auth_state] || '未知')
                item.userInfo = `[${faceAccessAuthType[relation_role] || '未知'}] ${relation_name}`
              })
              this.tableData = res.rows
            }
          } catch (err) {
            console.log(err)
          } finally {
            this.loading = false
          }
        },
        handleOp (handler, item) {
          this[handler] && this[handler](item)
        },
        handleReauthorize (record) {
          this.$Modal.confirm({
            loading: true,
            title: '提示',
            content: '确认重新授权?',
            onOk: () => {
              this.reauthorize(this.deviceInfo.room_id, this.deviceInfo.id, record.id)
            }
          })
        },
        async reauthorize (roomId, deviceId, authId) {
          const res = await http.req(api.face_access_retry, [roomId, deviceId, authId], null)
          this.$Modal.remove()
          if (res) {
            this.initData()
            this.$Message.success('授权下发成功')
          }
        },
        handleCancelAuth (record) {
          this.$Modal.confirm({
            loading: true,
            title: '提示',
            content: '确认取消授权?',
            onOk: () => {
              this.cancelAuth(this.deviceInfo.room_id, this.deviceInfo.id, record.id)
            }
          })
        },
        async cancelAuth (roomId, deviceId, authId) {
          const res = await http.req(api.face_access_delete_auth, [roomId, deviceId, authId], null)
          this.$Modal.remove()
          if (res) {
            this.initData()
            this.$Message.success('删除成功')
          }
        },
        handleMemberDetail ({ relation_name, relation_phone, relation_role, relation_id, face_file_id }) {
          this.memberDetail.visible = true
          this.memberDetail.userId = relation_id
          this.memberDetail.faceId = face_file_id
          this.memberDetail.roleId = relation_role
          this.memberDetail.name = relation_name
          this.memberDetail.phone = relation_phone
        }
      }
    }
</script>